package com.sinosoft.platform.common.util;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.*;

public class CollectionUtil {
	// 将map中的key按照字典顺序排序
	@SuppressWarnings({ "unchecked", "rawtypes" })
    public static <K, V> List<Map.Entry<K, V>> sortByKeys(Map<K, V> map) {
		List list = Arrays.asList(map.entrySet().toArray());
		//排序
		Collections.sort(list, new Comparator<Map.Entry<K, V>>() {   
		    @Override
			public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {      
		    	int result = 0;
		        //return (o2.getValue() - o1.getValue()); 
		    	if (o1.getKey() instanceof String) {
		    		result = ((String)o1.getKey()).compareTo((String)o2.getKey());
		    	} else if (o1.getKey() instanceof BigDecimal) {
		    		result = ((BigDecimal)o1.getKey()).compareTo((BigDecimal)o2.getKey());
		    	}
		        return result;
		    }
		}); 
		return list;
	}
	
	
	
	// Map的拷贝
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map copyMap(Map map) {
		Map m = new HashMap();
		for(Object o : map.keySet()){
		    m.put(o, map.get(o));
		}
		return m;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List getProjection(String fieldName, List srcList) throws Exception {
		List distList = new ArrayList();
		for (Object obj : srcList) {
			// 获取属性值
			Object value = ClassInvokeUtil.getMethodValue(obj, fieldName);
			distList.add(value);
		}
		return distList;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List filterList(List srcList, Map<String, Object> filterMap) throws Exception {
		List distList = new ArrayList();
		for (Object obj : srcList) {
			boolean matched = true;
			for(Map.Entry<String, Object> entry : filterMap.entrySet()){
			    String field = entry.getKey();
			    Object mappingValue = entry.getValue();
			    Object actualValue = ClassInvokeUtil.getMethodValue(obj, field);
			    if (!actualValue.equals(mappingValue)) {
			    	matched = false;
			    	break;
			    }
			}
			if (matched) {
				distList.add(obj);
			}
		}
		return distList;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T[] transformArray(String[] arr, Class<T> clz) {
		T[] tArr = (T[])Array.newInstance(clz, arr.length);
		for (int i = 0; i < arr.length; i++) {
			T obj = null;
			try {
				obj = StringUtil.transferString2PrimitiveType(arr[i], clz);
			} catch (Exception e) {
				e.printStackTrace();
			}
			tArr[i] = obj;
		}
		return tArr;
	}
}
